import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicInteger;

public class SyncThreadSem implements Runnable {
	private static final int TOT = 3, MAX = 50;
	private int ind;
	private Semaphore s;
	private AtomicInteger i;
	public SyncThreadSem(int ind, AtomicInteger i, Semaphore s) {
		this.ind = ind;
		this.i = i;
		this.s = s;
	}
	
	public static void main(String[] args) {
		Semaphore s = new Semaphore(1);
		AtomicInteger i = new AtomicInteger();
		for(int j = 0; j < TOT; j++)
			new Thread(new SyncThreadSem(j, i, s)).start();
	}

	@Override
	public void run() {
		int max = TOT * (MAX / TOT) + ind;
		if(max >= MAX)
			max -= TOT;
		while(i.get() <= max) {
			try {
				if(i.get() % TOT == ind) {
					s.acquire();
					System.out.println(ind + ": " + i.get());
					i.incrementAndGet();
					s.release();
				}
			} catch(Exception e) {
				System.out.println(e.getMessage());
			}
		}
	}
}
